<template>
  <div>
    <span class="wd-switch-core" :class="{ischeck: value}" @click="changecheck" ref="core">
      <span class="wd-switch-button"></span>
    </span>
    <input class="wd-switch-inp" type="checkbox" :name="name" ref="inp">
  </div>
</template>

<script>
export default {
  name: 'WdSwitch',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    activecolor: {
      type: String,
      default: ''
    },
    inactivecolor: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    }
  },
  methods: {
    setcolor () {
      if (this.activecolor || this.inactivecolor) {
        const color = this.value ? this.activecolor : this.inactivecolor
        this.$refs.core.style.borderColor = color
        this.$refs.core.style.backgroundColor = color
      }
    },
    async changecheck () {
      this.$emit('input', !this.value)
      await this.$nextTick()
      this.setcolor()
      // 让input的选中效果与按钮同步
      this.$refs.inp.checked = this.value
    }
  },
  mounted () {
    this.setcolor()
    // 让input的选中效果与按钮同步
    this.$refs.inp.checked = this.value
  }
}
</script>
<style scoped lang=scss>
  .wd-switch-core {
    display: inline-block;
    width: 40px;
    height: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 20px;
    background-color: #dcdfe6;
    transition: all .3s;
    cursor: pointer;
    .wd-switch-button {
      display: inline-block;
      width: 20px;
      height: 20px;
      background-color: #fff;
      border-radius: 50%;
      transition: all .3s;
    }
  }
  .wd-switch-core.ischeck {
    border-color: #409eff;
    background-color: #409eff;
    .wd-switch-button {
      transform: translateX(20px);
    }
  }
  /* 隐藏input */
  .wd-switch-inp {
    opacity: 0;
  }
</style>
